<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">

    
      <link rel="icon" href="/favicon.png" />
    

    <title>
        
          CODE&#39;NOTE
        
    </title>

    <!-- Spectre.css framework -->
    <link href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre.min.css" rel="stylesheet">
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre-exp.min.css" rel="stylesheet">
    <link href="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre-icons.min.css" rel="stylesheet">

    <!-- theme css & js -->
    
<link rel="stylesheet" href="/css/book.css">

    
<script src="/js/book.js"></script>


    <!-- tocbot -->
    <script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/tocbot/4.18.2/tocbot.min.js"></script>
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/tocbot/4.18.2/tocbot.css" rel="stylesheet">
    
    <!-- katex -->    
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/KaTeX/0.15.2/katex.min.css" rel="stylesheet">

    
    
<script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/zooming/2.1.1/zooming.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const zooming = new Zooming()
    zooming.listen('.book-content img')
})
</script>

<meta name="generator" content="Hexo 6.1.0"></head>

<body>

<div class="book-container">
  <div class="book-sidebar">
    <div class="book-brand">
  <a href="/">
    <img src="/favicon.png">
    <span>CODE&#39;NOTE</span>
  </a>
</div>
    <div id="menu" class="book-menu hide">
  <h2 id="☘️-Home">☘️ <a href="/">Home</a></h2>
<h2 id="Go">Go</h2>
<ul>
<li><a href="/go/01%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA">0.1 开发环境搭建</a></li>
<li><a href="/go/02%E5%8F%98%E9%87%8F%E5%92%8C%E5%B8%B8%E9%87%8F">0.2 变量和常量</a></li>
<li><a href="/go/03%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B">0.3 基本数据类型</a></li>
<li><a href="/go/04%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E5%92%8C%E8%BF%90%E7%AE%97%E7%AC%A6">0.4 流程控制和运算符</a></li>
<li><a href="/go/05%E6%95%B0%E7%BB%84">0.5 数组</a></li>
<li><a href="/go/06%E5%88%87%E7%89%87">0.6 切片</a></li>
<li><a href="/go/07map">0.7 map</a></li>
<li><a href="/go/08%E5%87%BD%E6%95%B0">0.8 函数</a></li>
<li><a href="/go/09%E6%8C%87%E9%92%88">0.9 指针</a></li>
<li><a href="/go/10%E5%8F%8D%E5%B0%84">1.0 反射</a></li>
<li><a href="/go/11%E7%BB%93%E6%9E%84%E4%BD%93">1.1 结构体</a></li>
<li><a href="/go/12%E6%8E%A5%E5%8F%A3">1.2 接口</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/goroutine">1.3 goroutine</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/channel">1.4 channel</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/%E5%B9%B6%E5%8F%91%E5%AE%89%E5%85%A8%E5%92%8C%E9%94%81">1.5 并发安全和锁</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/%E5%8E%9F%E5%AD%90%E6%93%8D%E4%BD%9C">1.6 原子操作</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/GPM%E5%8E%9F%E7%90%86%E4%B8%8E%E8%B0%83%E5%BA%A6">1.7 GPM与调度分析</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/CSP%E5%B9%B6%E5%8F%91%E6%A8%A1%E5%9E%8B">1.8 CSP并发模型</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/fmt">标准库fmt</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/flag">标准库flag</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/time">标准库time</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/go_%E6%A0%87%E5%87%86%E5%BA%93log">标准库log</a></li>
</ul>
<!-- ##
## .NET

* [C# 入门基础合集](/dotnet/基础合集)
* [C# 面向对象](/dotnet/面向对象)
* [C# 数据结构](/dotnet/数据结构)
* [C# 泛型技术](/dotnet/泛型技术)
* [C# 反射技术](/dotnet/反射技术)
* [C# 多线程开发](/dotnet/多线程开发)
* [C# 多线程之线程同步技术](/dotnet/多线程之线程同步技术)
* [C# 委托和事件详解](/dotnet/委托和事件详解)
* [C# 并行编程](/dotnet/并行编程)
* [C# 异步编程](/dotnet/异步编程)
* [C# 值类型和引用类型内存分配](/dotnet/值类型和引用类型的内存分配)
* [1.1 DataProtection简介](/dotnet/1.1DataProtection简介)
* [1.2 DataProtection方法介绍](/dotnet/1.2DataProtection方法介绍)
* [1.3 落地实践及多环境调试](/dotnet/1.3落地实践及多环境调试)
* [1.4 UserSecrets](/dotnet/1.4UserSecrets)
* [1.5 数据保护方案](/dotnet/1.5基于DataProtection的数据保护方案)
* [1.6 集成AzureDevops](/dotnet/1.6方案实践及集成AzureDevops管道)


ELK Stack

* [ElastaticSearch入门](/elk/1.1ElastaticSearch入门)
* [ElastaticSearch配置](/elk/1.2ElastaticSearch配置)
* [使用Kibana操作ES](/elk/1.3使用Kibana操作ES)
 ## Docker

* [1.1 Docker概念及安装](/docker/1.1Docker概念及安装)
* [1.2 Docker镜像](/docker/1.2Docker镜像)
* [1.3 Docker容器](/docker/1.3Docker容器)
* [1.4 Docker仓库](/docker/1.4Docker仓库)
* [1.5 Docker数据管理](/docker/1.5Docker数据管理)
* [1.6 Docker容器四种网络模式](/docker/1.6Docker容器四种网络模式)
* [1.7 Docker高级网络配置](/docker/1.7Docker高级网络配置)
* [1.8 Dockerfile](/docker/1.8Dockerfile)
* [1.9 DockerCompose](/docker/1.9Docker三剑客之DockerCompose)
* [2.0 DockerMachine](/docker/2.0Docker三剑客之DockerMachine)
* [2.1 DockerSwarm](/docker/2.1Docker三剑客之DockerSwarm)
* [2.2 Docker常用命令](/docker/2.2Docker常用命令)
* [Portainer可视化面板](/docker/Portainer可视化面板)
* [1.6 Docker四种网络模式](/docker/1.6Docker容器网络模式)
* [1.7 Docker高级网络配置](/docker/1.7Docker高级网络配置)
* [1.8 Dockerfile](/docker/1.8Dockerfile)
* [1.9 DockerCompose](/docker/1.9DockerCompose)
* [2.0 DockerMachine](/docker/2.0DockerMachine)
* [2.1 DockerSwarm](/docker/2.1DockerSwarm)
* [2.2 Docker常用命令](/docker/2.2Docker常用命令)
* [Portainer可视化面板](/docker/Portainer可视化面板) 

## Linux

* [Centos安装](/linux/Centos安装)
* [Linux目录说明](/linux/Linux目录说明)
* [Centos网络配置](/linux/Centos网络配置)
* [Centos7升级gcc版本](/linux/Centos7升级gcc版本)
* [Linux常用命令](/linux/Linux常用命令)

## RabbitMQ

* [1.1 RabbitMQ概念及安装](/rabbitMq/1.1RabbitMQ概念及安装)
* [1.2 工作模式介绍](/rabbitMq/1.2工作模式介绍)
* [1.3 消息确认及持久化](/rabbitMq/1.3消息确认及持久化)
* [1.4 两种消费模式和QOS](/rabbitMq/1.4两种消费模式和QOS的实现)
* [1.5 Channel常见方法](/rabbitMq/1.5Channel常见方法)
* [1.6 RabbitMQ常用命令](/rabbitMq/1.6RabbitMQ常用命令)
* [1.7 RabbitMQ常见策略](/rabbitMq/1.7RabbitMQ常见策略)
* [1.8 RabbitMQ常见问题](/rabbitMq/1.8RabbitMQ常见问题)
* [1.9 RabbitMQ集群方案](/rabbitMq/1.9RabbitMQ集群方案)
* [客户端连接RabbitMQ](/rabbitMq/客户端连接RabbitMQ)

## Redis

* [1.1 NoSql概述](/redis/1.1NoSql概述)
* [1.2 Redis安装](/redis/1.2Redis安装)
* [1.3 Redis基本数据类型](/redis/1.3Redis基本数据类型)
* [1.4 Redis特殊数据类型](/redis/1.4Redis特殊数据类型)
* [1.5 Redis事务操作](/redis/1.5Redis事务操作)
* [1.6 Redis配置文件详解](/redis/1.6Redis配置文件详解)
* [1.7 Redis持久化](/redis/1.7Redis持久化)
* [1.8 Redis发布订阅](/redis/1.8Redis发布订阅)
* [1.9 Redis集群方案](/redis/1.9Redis集群方案)
* [1.10 Redis常见问题](/redis/1.10Redis常见问题)
* [客户端连接Redis](/redis/客户端连接Redis)
* [使用Docker搭建Redis集群](/redis/使用Docker搭建Redis集群)

## MicroService

* [1.1 微服务之项目搭建](/microservice/1.1微服务入门之项目搭建)
* [1.2 微服务之服务注册发现](/microservice/1.2微服务入门之服务注册与发现)
* [1.3 微服务之网关](/microservice/1.3微服务入门之网关)
* [1.4 微服务之事件总线](/microservice/1.4微服务入门之事件总线)
* [1.5 微服务之DockerCompose](/microservice/1.5微服务入门之DockerCompose)
* [Consul服务注册发现](/microservice/Consul服务注册发现)

## Test

* [单元测试](/test/单元测试)
* [集成测试](/test/集成测试)
* [压力测试k6](/test/压力测试k6)
* [自动化UI测试](/test/自动化UI测试) -->

</div>


<script src="/js/book-menu.js"></script>

  </div>

  <div class="sidebar-toggle" onclick="sidebar_toggle()" onmouseover="add_inner()" onmouseleave="remove_inner()">
  <div class="sidebar-toggle-inner"></div>
</div>

<script>
function add_inner() {
  let inner = document.querySelector('.sidebar-toggle-inner')
  inner.classList.add('show')  
}

function remove_inner() {
  let inner = document.querySelector('.sidebar-toggle-inner')
  inner.classList.remove('show')
}

function sidebar_toggle() {
    let sidebar_toggle = document.querySelector('.sidebar-toggle')
    let sidebar = document.querySelector('.book-sidebar')
    let content = document.querySelector('.off-canvas-content')
    if (sidebar_toggle.classList.contains('extend')) { // show
        sidebar_toggle.classList.remove('extend')
        sidebar.classList.remove('hide')
        content.classList.remove('extend')
    }
    else { // hide
        sidebar_toggle.classList.add('extend')
        sidebar.classList.add('hide')
        content.classList.add('extend')
    }
}
</script>

  <div class="off-canvas-content">
    <div class="columns">
      <div class="column col-10 col-lg-12">
        <div class="book-navbar">
          <!-- For Responsive Layout -->

<header class="navbar">
  <section class="navbar-section">
    <a onclick="open_sidebar()">
      <i class="icon icon-menu"></i>
    </a>
  </section>
</header>

        </div>
        <div class="book-content">
          <div class="book-post">
  <p>接口（interface）定义了一个对象的行为规范，只定义规范具体对象来实现规范的细节。Go语言中接口（interface）是一种抽象类型。与C#中接口的定义是一样的，相较于具体类型比如字符串、切片、结构体等（更注重“我是什么”），接口类型更注重“能做什么”。接口类型像是一种约定。Go语言中提倡使用面向接口的编程方式实现解耦。</p>
<h1 id="接口类型">接口类型</h1>
<p>接口是一种由程序员定义的类型，一个接口类型就是一组方法的集合，它规定了需要实现的所有方法。相较于使用结构体类型，当使用接口类型说明：<strong>相比于它是什么更关心它能做什么</strong>。</p>
<h1 id="接口定义">接口定义</h1>
<p>每个接口类型由任意个方法签名组成，定义格式如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> 接口类型名 <span class="keyword">interface</span>&#123;</span><br><span class="line">    方法名<span class="number">1</span>( 参数列表<span class="number">1</span> ) 返回值列表<span class="number">1</span></span><br><span class="line">    方法名<span class="number">2</span>( 参数列表<span class="number">2</span> ) 返回值列表<span class="number">2</span></span><br><span class="line">    …</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中：</p>
<ul>
<li>接口类型名：Go语言的接口在命名时，一般会在单词后面添加<code>er</code>，就像C#中接口定义通常以<code>I</code> 开头，接口名要能突出该接口的类型含义</li>
<li>方法名：当方法名首字母是大写且这个接口类型名首字母也是大写时，这个方法可以被接口所在的包（package）之外的代码访问</li>
<li>参数列表、返回值列表：参数列表和返回值列表中的参数变量名可以省略</li>
</ul>
<p>比如，定义一个包含<code>Write</code>方法的<code>Writer</code>接口</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Writer <span class="keyword">interface</span>&#123;</span><br><span class="line">    Write([]<span class="type">byte</span>) <span class="type">error</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当看到一个<code>Writer</code>接口类型的值时，不知道它是什么，唯一知道的就是可以通过调用它的<code>Write</code>方法来做一些事。</p>
<h1 id="实现接口的条件">实现接口的条件</h1>
<p>接口规定了一个<strong>需要实现的方法列表</strong>，<strong>Go 语言中一个类型只要实现了接口中规定的所有方法，就称它实现了这个接口</strong>。在C#或者Java语言中都需要显式声明类实现了哪些接口，Go语言中则使用隐式声明的方式实现接口。</p>
<h1 id="值接收者和指针接收者">值接收者和指针接收者</h1>
<p>之前介绍了在定义结构体方法时既可以使用值接收者也可以使用指针接收者。那么对于实现接口来说使用值接收者和使用指针接收者有什么区别呢？通过一个例子来看一下。</p>
<p>我们定义一个<code>Mover</code>接口，它包含一个<code>Move</code>方法。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Move <span class="keyword">interface</span> &#123;</span><br><span class="line">	Move()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="值接收者实现接口">值接收者实现接口</h2>
<p>定义一个<code>Dog</code>结构体类型，并使用值接收者为其定义一个<code>Move</code>方法</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Dog <span class="keyword">struct</span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Move 使用值接收者定义Move方法实现Mover接口</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(d Dog)</span></span> Move() &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;狗会动&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此时实现<code>Mover</code>接口的是<code>Dog</code>类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x Mover    <span class="comment">// 声明一个Mover类型的变量x</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> d1 = Dog&#123;&#125; <span class="comment">// d1是Dog类型</span></span><br><span class="line">x = d1         <span class="comment">// 可以将d1赋值给变量x</span></span><br><span class="line">x.Move()</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> d2 = &amp;Dog&#123;&#125; <span class="comment">// d2是Dog指针类型</span></span><br><span class="line">x = d2          <span class="comment">// 也可以将d2赋值给变量x</span></span><br><span class="line">x.Move()</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">狗会动</span><br><span class="line">狗会动</span><br></pre></td></tr></table></figure>
<p>上面的代码中可以发现，使用值接收者实现接口之后，不管是结构体类型还是对应的结构体指针类型的变量都可以赋值给该接口变量。</p>
<h2 id="指针接收者实现接口">指针接收者实现接口</h2>
<p>再来测试一下使用指针接收者实现接口有什么区别。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Cat 猫结构体类型</span></span><br><span class="line"><span class="keyword">type</span> Cat <span class="keyword">struct</span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Move 使用指针接收者定义Move方法实现Mover接口</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(c *Cat)</span></span> Move() &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;猫会动&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此时实现<code>Mover</code>接口的是<code>*Cat</code>类型，可以将<code>*Cat</code>类型的变量直接赋值给<code>Mover</code>接口类型的变量<code>x</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> c2 = &amp;Cat&#123;&#125; <span class="comment">// c2是*Cat类型</span></span><br><span class="line">x = c2          <span class="comment">// 可以将c2当成Mover类型</span></span><br><span class="line">x.Move()</span><br></pre></td></tr></table></figure>
<p>但是不能将<code>Cat</code>类型的变量赋值给<code>Mover</code>接口类型的变量<code>x</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 下面的代码无法通过编译</span></span><br><span class="line"><span class="keyword">var</span> c1 = Cat&#123;&#125; <span class="comment">// c1是Cat类型</span></span><br><span class="line">x = c1         <span class="comment">// 不能将c1当成Mover类型</span></span><br></pre></td></tr></table></figure>
<p>由于Go语言中有对指针求值的语法糖，对于值接收者实现的接口，无论使用值类型还是指针类型都没有问题。但是并不总是能对一个值求址，所以对于指针接收者实现的接口要额外注意。</p>
<h1 id="类型与接口">类型与接口</h1>
<h2 id="一个类型实现多个接口">一个类型实现多个接口</h2>
<p>一个类型可以同时实现多个接口，而接口间彼此独立，不知道对方的实现。例如狗不仅可以叫，还可以动。可以分别定义<code>Sayer</code>接口和<code>Mover</code>接口，代码示例如下。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Sayer 接口</span></span><br><span class="line"><span class="keyword">type</span> Sayer <span class="keyword">interface</span> &#123;</span><br><span class="line">	Say()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Mover 接口</span></span><br><span class="line"><span class="keyword">type</span> Mover <span class="keyword">interface</span> &#123;</span><br><span class="line">	Move()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>Dog</code>既可以实现<code>Sayer</code>接口，也可以实现<code>Mover</code>接口。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Dog <span class="keyword">struct</span> &#123;</span><br><span class="line">	name <span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Move 使用值接收者定义Move方法实现Mover接口</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(d Dog)</span></span> Move() &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;狗会动&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 实现Sayer接口</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(d Dog)</span></span> Say() &#123;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;%s会叫汪汪汪\n&quot;</span>, d.name)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>同一个类型实现不同的接口互相不影响使用。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> d = Dog&#123;Name: <span class="string">&quot;旺财&quot;</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> s Sayer = d</span><br><span class="line"><span class="keyword">var</span> m Mover = d</span><br><span class="line"></span><br><span class="line">s.Say()  <span class="comment">// 对Sayer类型调用Say方法</span></span><br><span class="line">m.Move() <span class="comment">// 对Mover类型调用Move方法</span></span><br></pre></td></tr></table></figure>
<h2 id="多种类型实现同一接口">多种类型实现同一接口</h2>
<p>Go语言中不同的类型还可以实现同一接口。例如不仅狗可以动，汽车也可以动。可以使用如下代码体现：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 实现Mover接口</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(d Dog)</span></span> Move() &#123;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;%s会动\n&quot;</span>, d.Name)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Car 汽车结构体类型</span></span><br><span class="line"><span class="keyword">type</span> Car <span class="keyword">struct</span> &#123;</span><br><span class="line">	Brand <span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Move Car类型实现Mover接口</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(c Car)</span></span> Move() &#123;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;%s速度70迈\n&quot;</span>, c.Brand)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样在代码中就可以把狗和汽车当成一个会动的类型来处理，不必关注它们具体是什么，只需要调用<code>Move</code>方法即可。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x Mover</span><br><span class="line"></span><br><span class="line">x = Dog&#123;name: <span class="string">&quot;旺财&quot;</span>&#125;</span><br><span class="line">x.Move()</span><br><span class="line"></span><br><span class="line">x = Car&#123;brand: <span class="string">&quot;宝马&quot;</span>&#125;</span><br><span class="line">x.Move()</span><br></pre></td></tr></table></figure>
<p>一个接口的所有方法，不一定需要由一个类型完全实现，接口的方法可以通过在类型中嵌入其他类型或者结构体来实现。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  洗衣机</span></span><br><span class="line"><span class="keyword">type</span> WashingMachine <span class="keyword">interface</span> &#123;</span><br><span class="line">    <span class="comment">// 清洗</span></span><br><span class="line">	wash()</span><br><span class="line">    <span class="comment">// 烘干</span></span><br><span class="line">	dry()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 海尔洗衣机</span></span><br><span class="line"><span class="keyword">type</span> haier <span class="keyword">struct</span> &#123;</span><br><span class="line">	dryer <span class="comment">// 嵌入甩干器</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 实现WashingMachine接口的wash()方法</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(h haier)</span></span> wash() &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;洗刷刷&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 甩干机</span></span><br><span class="line"><span class="keyword">type</span> dryer <span class="keyword">struct</span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(d dryer)</span></span> dry() &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;甩一甩&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="接口组合">接口组合</h1>
<p>接口与接口之间可以通过互相嵌套形成新的接口类型，例如Go标准库<code>io</code>源码中就有很多接口之间互相组合的示例。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// src/io/io.go</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Reader <span class="keyword">interface</span> &#123;</span><br><span class="line">	Read(p []<span class="type">byte</span>) (n <span class="type">int</span>, err <span class="type">error</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Writer <span class="keyword">interface</span> &#123;</span><br><span class="line">	Write(p []<span class="type">byte</span>) (n <span class="type">int</span>, err <span class="type">error</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Closer <span class="keyword">interface</span> &#123;</span><br><span class="line">	Close() <span class="type">error</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ReadWriter 是组合Reader接口和Writer接口形成的新接口类型</span></span><br><span class="line"><span class="keyword">type</span> ReadWriter <span class="keyword">interface</span> &#123;</span><br><span class="line">	Reader</span><br><span class="line">	Writer</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ReadCloser 是组合Reader接口和Closer接口形成的新接口类型</span></span><br><span class="line"><span class="keyword">type</span> ReadCloser <span class="keyword">interface</span> &#123;</span><br><span class="line">	Reader</span><br><span class="line">	Closer</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// WriteCloser 是组合Writer接口和Closer接口形成的新接口类型</span></span><br><span class="line"><span class="keyword">type</span> WriteCloser <span class="keyword">interface</span> &#123;</span><br><span class="line">	Writer</span><br><span class="line">	Closer</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对于这种由多个接口类型组合形成的新接口类型，同样只需要实现新接口类型中规定的所有方法就算实现了该接口类型。</p>
<p>接口也可以作为结构体的一个字段，看一段Go标准库<code>sort</code>源码中的示例。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// src/sort/sort.go</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Interface 定义通过索引对元素排序的接口类型</span></span><br><span class="line"><span class="keyword">type</span> Interface <span class="keyword">interface</span> &#123;</span><br><span class="line">    Len() <span class="type">int</span></span><br><span class="line">    Less(i, j <span class="type">int</span>) <span class="type">bool</span></span><br><span class="line">    Swap(i, j <span class="type">int</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// reverse 结构体中嵌入了Interface接口</span></span><br><span class="line"><span class="keyword">type</span> reverse <span class="keyword">struct</span> &#123;</span><br><span class="line">    Interface</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过在结构体中嵌入一个接口类型，从而让该结构体类型实现了该接口类型，并且还可以改写该接口的方法。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Less 为reverse类型添加Less方法，重写原Interface接口类型的Less方法</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(r reverse)</span></span> Less(i, j <span class="type">int</span>) <span class="type">bool</span> &#123;</span><br><span class="line">	<span class="keyword">return</span> r.Interface.Less(j, i)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>Interface</code>类型原本的<code>Less</code>方法签名为<code>Less(i, j int) bool</code>，此处重写为<code>r.Interface.Less(j, i)</code>，即通过将索引参数交换位置实现反转。</p>
<p>在这个示例中还有一个需要注意的地方是<code>reverse</code>结构体本身是不可导出的（结构体类型名称首字母小写），<code>sort.go</code>中通过定义一个可导出的<code>Reverse</code>函数来让使用者创建<code>reverse</code>结构体实例。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">Reverse</span><span class="params">(data Interface)</span></span> Interface &#123;</span><br><span class="line">	<span class="keyword">return</span> &amp;reverse&#123;data&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样做的目的是保证得到的<code>reverse</code>结构体中的<code>Interface</code>属性一定不为<code>nil</code>，否者<code>r.Interface.Less(j, i)</code>就会出现空指针panic。</p>
<p>此外在Go内置标准库<code>database/sql</code>中也有很多类似的结构体内嵌接口类型的使用示例。</p>
<h1 id="空接口">空接口</h1>
<p>空接口是指没有定义任何方法的接口类型。因此任何类型都可以视为实现了空接口。也正是因为这个特性，空接口类型的变量可以存储任意类型的值。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Any 不包含任何方法的空接口类型</span></span><br><span class="line"><span class="keyword">type</span> Any <span class="keyword">interface</span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 空接口类型的变量可以存储任意类型的值</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">emptyInterfaceTest</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 声明空接口类型变量</span></span><br><span class="line">	<span class="keyword">var</span> x Any</span><br><span class="line"></span><br><span class="line">	x = <span class="string">&quot;你好&quot;</span> <span class="comment">// 字符串型</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;type:%T value:%v\n&quot;</span>, x, x)</span><br><span class="line">	x = <span class="number">100</span> <span class="comment">// int型</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;type:%T value:%v\n&quot;</span>, x, x)</span><br><span class="line">	x = <span class="literal">true</span> <span class="comment">// 布尔型</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;type:%T value:%v\n&quot;</span>, x, x)</span><br><span class="line">	x = Person&#123;&#125; <span class="comment">// 结构体类型</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;type:%T value:%v\n&quot;</span>, x, x)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通常在使用空接口类型时不必使用<code>type</code>关键字声明，可以像下面的代码一样直接使用<code>interface&#123;&#125;</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x <span class="keyword">interface</span>&#123;&#125;  <span class="comment">// 声明一个空接口类型变量x</span></span><br></pre></td></tr></table></figure>
<h2 id="空接口作为函数参数">空接口作为函数参数</h2>
<p>使用空接口实现可以接收任意类型的函数参数。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 空接口作为函数参数</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">print</span><span class="params">(a <span class="keyword">interface</span>&#123;&#125;)</span></span> &#123;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;type:%T value:%v\n&quot;</span>, a, a)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="空接口作为map的值">空接口作为map的值</h2>
<p>使用空接口实现可以保存任意值的字典。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">emptyInterfaceTest4</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> person = <span class="built_in">make</span>(<span class="keyword">map</span>[<span class="type">string</span>]<span class="keyword">interface</span>&#123;&#125;)</span><br><span class="line">	person[<span class="string">&quot;name&quot;</span>] = <span class="string">&quot;wangpengliang&quot;</span></span><br><span class="line">	person[<span class="string">&quot;age&quot;</span>] = <span class="number">18</span></span><br><span class="line">	person[<span class="string">&quot;married&quot;</span>] = <span class="literal">false</span></span><br><span class="line">	fmt.Println(person)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="接口值">接口值</h1>
<p>由于接口类型的值可以是任意一个实现了该接口的类型值，所以接口值除了需要记录具体<strong>值</strong>之外，还需要记录这个值属于的<strong>类型</strong>。也就是说接口值由“类型”和“值”组成，鉴于这两部分会根据存入值的不同而发生变化，称之为接口的<code>动态类型</code>和<code>动态值</code>。</p>
<p><img src="/images/2022-03-30-16-00-55.png" alt=""></p>
<p>通过一个示例来加深对接口值的理解，示例代码中，定义了一个<code>Mover</code>接口类型和两个实现了该接口的<code>Dog</code>和<code>Car</code>结构体类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Mover <span class="keyword">interface</span> &#123;</span><br><span class="line">	Move()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Dog <span class="keyword">struct</span> &#123;</span><br><span class="line">	Name <span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(d *Dog)</span></span> Move() &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;狗在跑~&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Car <span class="keyword">struct</span> &#123;</span><br><span class="line">	Brand <span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(c *Car)</span></span> Move() &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;汽车在跑~&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>首先创建一个<code>Mover</code>接口类型的变量<code>m</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> m Mover</span><br></pre></td></tr></table></figure>
<p>此时，接口变量<code>m</code>是接口类型的零值，也就是它的类型和值部分都是<code>nil</code>，就如下图所示。<br>
<img src="/images/2022-03-30-11-03-47.png" alt=""></p>
<p>可以使用<code>m == nil</code>来判断此时的接口值是否为空。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fmt.Println(m == <span class="literal">nil</span>)  <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p><strong>注意</strong>：不能对一个空接口值调用任何方法，否则会产生panic。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">m.Move() <span class="comment">// panic: runtime error: invalid memory address or nil pointer dereference</span></span><br></pre></td></tr></table></figure>
<p>接下来将一个<code>*Dog</code>结构体指针赋值给变量<code>m</code>，此时<code>m</code>的动态类型会被设置为<code>*Dog</code>，动态值为结构体变量的拷贝。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">m = &amp;Dog&#123;Name: <span class="string">&quot;旺财&quot;</span>&#125;</span><br></pre></td></tr></table></figure>
<p><img src="/images/2022-03-30-15-54-50.png" alt=""></p>
<p>然后给接口变量<code>m</code>赋值为一个<code>*Car</code>类型的值。此时接口值的动态类型为<code>*Car</code>，动态值为<code>nil</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">m = <span class="built_in">new</span>(Car)</span><br></pre></td></tr></table></figure>
<p><img src="/images/2022-03-30-15-55-29.png" alt=""></p>
<p><strong>注意</strong>：此时接口变量<code>m</code>与<code>nil</code>并不相等，因为它只是动态值的部分为<code>nil</code>，而动态类型部分保存着对应值的类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fmt.Println(m == <span class="literal">nil</span>) <span class="comment">// false</span></span><br></pre></td></tr></table></figure>
<p>接口值是支持相互比较的，当且仅当接口值的动态类型和动态值都相等时才相等。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> (</span><br><span class="line">	x Mover2 = <span class="built_in">new</span>(Dog2)</span><br><span class="line">	y Mover2 = <span class="built_in">new</span>(Car2)</span><br><span class="line">)</span><br><span class="line">fmt.Println(x == y) <span class="comment">// false</span></span><br></pre></td></tr></table></figure>
<p>有一种特殊情况需要特别注意，如果接口值的保存的动态类型相同，但是这个动态类型不支持互相比较（比如切片），那么对它们相互比较时就会引发 <code>panic</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> z <span class="keyword">interface</span>&#123;&#125; = []<span class="type">int</span>&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;</span><br><span class="line">fmt.Println(z == z) <span class="comment">// panic: runtime error: comparing uncomparable type []int</span></span><br></pre></td></tr></table></figure>
<h1 id="类型断言">类型断言</h1>
<p>接口值可能赋值为任意类型的值，如何从接口值获取其存储的具体数据呢？可以借助标准库 <code>fmt</code> 包的格式化打印获取到接口值的动态类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> m Mover</span><br><span class="line"></span><br><span class="line">m = &amp;Dog&#123;Name: <span class="string">&quot;旺财&quot;</span>&#125;</span><br><span class="line">fmt.Printf(<span class="string">&quot;%T\n&quot;</span>, m) <span class="comment">// *main.Dog</span></span><br><span class="line"></span><br><span class="line">m = <span class="built_in">new</span>(Car)</span><br><span class="line">fmt.Printf(<span class="string">&quot;%T\n&quot;</span>, m) <span class="comment">// *main.Car</span></span><br></pre></td></tr></table></figure>
<p>而<code>fmt</code>包内部其实是使用反射的机制在程序运行时获取到动态类型的名称。而想要从接口值中获取到对应的实际值需要使用类型断言，其语法格式如下。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">x.(T)</span><br></pre></td></tr></table></figure>
<p>其中：</p>
<ul>
<li>x：表示接口类型的变量</li>
<li>T：表示断言<code>x</code>可能是的类型。</li>
</ul>
<p>该语法返回两个参数，第一个参数是<code>x</code>转化为<code>T</code>类型后的变量，第二个值是一个布尔值，若为<code>true</code>则表示断言成功，为<code>false</code>则表示断言失败。</p>
<p>比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> n Mover = &amp;Dog&#123;Name: <span class="string">&quot;旺财&quot;</span>&#125;</span><br><span class="line">v, ok := n.(*Dog)</span><br><span class="line"><span class="keyword">if</span> ok &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;类型断言成功&quot;</span>)</span><br><span class="line">	v.Name = <span class="string">&quot;富贵&quot;</span> <span class="comment">// 变量v是*Dog类型</span></span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;类型断言失败&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果对一个接口值有多个实际类型需要判断，推荐使用<code>switch</code>语句来实现。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// justifyType 对传入的空接口类型变量x进行类型断言</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">justifyType</span><span class="params">(x <span class="keyword">interface</span>&#123;&#125;)</span></span> &#123;</span><br><span class="line">	<span class="keyword">switch</span> v := x.(<span class="keyword">type</span>) &#123;</span><br><span class="line">	<span class="keyword">case</span> <span class="type">string</span>:</span><br><span class="line">		fmt.Printf(<span class="string">&quot;x is a string，value is %v\n&quot;</span>, v)</span><br><span class="line">	<span class="keyword">case</span> <span class="type">int</span>:</span><br><span class="line">		fmt.Printf(<span class="string">&quot;x is a int is %v\n&quot;</span>, v)</span><br><span class="line">	<span class="keyword">case</span> <span class="type">bool</span>:</span><br><span class="line">		fmt.Printf(<span class="string">&quot;x is a bool is %v\n&quot;</span>, v)</span><br><span class="line">	<span class="keyword">default</span>:</span><br><span class="line">		fmt.Println(<span class="string">&quot;unsupport type！&quot;</span>)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>由于接口类型变量能够动态存储不同类型值的特点，所以很多人会滥用接口类型（特别是空接口）来实现编码过程中的便捷。只有当有两个或两个以上的具体类型必须以相同的方式进行处理时才需要定义接口。切记不要为了使用接口类型而增加不必要的抽象，导致不必要的运行时损耗。</p>
<p>在 Go 语言中接口是一个非常重要的概念和特性，使用接口类型能够实现代码的抽象和解耦，也可以隐藏某个功能的内部实现，但是缺点就是在查看源码的时候，不太方便查找到具体实现接口的类型。<strong>切记</strong>：接口是一种类型，一种抽象的类型。它是一个只要求实现特定方法的抽象类型。</p>
<p><strong>小技巧：</strong> 下面的代码可以在程序编译阶段验证某一结构体是否满足特定的接口类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 摘自gin框架routergroup.go</span></span><br><span class="line"><span class="keyword">type</span> IRouter <span class="keyword">interface</span>&#123; ... &#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> RouterGroup <span class="keyword">struct</span> &#123; ... &#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> _ IRouter = &amp;RouterGroup&#123;&#125;  <span class="comment">// 确保RouterGroup实现了接口IRouter</span></span><br></pre></td></tr></table></figure>
<p>上面的代码中也可以使用 <code>var _ IRouter = (*RouterGroup)(nil)</code> 进行验证。</p>

</div>


  <div class="book-comments">
    




  </div>



<script src="/js/book-post.js"></script>

        </div>
      </div>
      <div class="column col-2 hide-lg">
        <div class="book-post-info">
  
    <div class="book-post-meta">

  <div class="author">

    <!-- Author image -->
    <div class="author-img">
      
        <figure
          class="avatar avatar-lg"
          data-initial="W"
          style="background-color: #3b4351;">
        </figure>
      
    </div>

    <!-- Author title -->
    <div class="author-title">
      <div>WangPengLiang</div>
      <div>2022-03-30</div>
    </div>
  </div>

  

  <div class="divider"></div>
</div>
  

  <div class="book-tocbot">
</div>
<div class="book-tocbot-menu">
  <a class="book-toc-expand" onclick="expand_toc()">Expand all</a>
  <a onclick="go_top()">Back to top</a>
  <a onclick="go_bottom()">Go to bottom</a>
</div>


<script src="/js/book-toc.js"></script>

</div>
      </div>
    </div>
  </div>
  
  <a class="off-canvas-overlay" onclick="hide_canvas()"></a>
</div>

</body>
</html>


<script src="/js/book.js"></script>
